<script setup lang="ts">
import { ref, provide } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import headerNavBar from '@/components/headerNavBar.vue';
import { useMountUserInfo } from '@/composables/useMountUserInfo';
import type { SubItem, AnimationPublish, CancelAnimationPublish } from '@/types/animationPublish';

const router = useRouter();
const route = useRoute();

// 首页挂载userInfo
useMountUserInfo();

// 缓存页面
const keepAlivePages = router
  .getRoutes()
  .filter((v) => /^\/hbMarket/.test(v.path) && v.meta?.keepAlive)
  .map((v) => v.name || '') as string[];
// tabBar页面
const tabBarPages = ['hbMarketHome', 'hbMarketMy'];

const getActive = () => {
  switch (route.name) {
    case 'hbMarketHome':
      return 0;
    case 'hbMarketMy':
      return 1;
  }
};
const active = ref(getActive());

router.afterEach(() => {
  active.value = getActive();
});

/**
 * 使用观察者模式订阅生命周期onAfterEnter
 */

// 订阅者列表
const subList = ref<Set<SubItem>>(new Set());

// 发布方法用于订阅onAfterEnter生命周期
provide<AnimationPublish>('animationPublish', (key, fn) => {
  subList.value.add({ key, fn });
});

// 取消订阅onAfterEnter生命周期
provide<CancelAnimationPublish>('cancelAnimationPublish', (key) => {
  subList.value.forEach((v) => {
    if (v.key === key) {
      subList.value.delete(v);
    }
  });
});

const onAfterEnter = () => {
  subList.value.forEach(({ fn }) => fn());
};
</script>
<template>
  <div class="hbMarket">
    <headerNavBar />
    <main>
      <router-view v-slot="{ Component }">
        <transition name="fade" @after-enter="onAfterEnter">
          <keep-alive :include="keepAlivePages">
            <component :is="Component" />
          </keep-alive>
        </transition>
      </router-view>
    </main>
    <template v-if="tabBarPages.includes(route.name as string)">
      <van-tabbar v-model="active" active-color="#EC2D69" placeholder safe-area-inset-bottom>
        <van-tabbar-item icon="wap-home" to="/hbMarket/home" replace>首页</van-tabbar-item>
        <van-tabbar-item icon="contact" to="/hbMarket/my" replace>我的</van-tabbar-item>
      </van-tabbar>
    </template>
  </div>
</template>
<style lang="less" scoped>
.hbMarket {
  height: 100vh;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  main {
    flex: 1;
    overflow-y: auto;
    scrollbar-width: thin;
    scrollbar-color: transparent transparent;
  }
  /* WebKit浏览器（Chrome，Safari等） */
  main::-webkit-scrollbar {
    width: 0px;
  }

  main::-webkit-scrollbar-track {
    background-color: transparent;
  }

  main::-webkit-scrollbar-thumb {
    background-color: transparent;
  }
}
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.2s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}
</style>
